<template>
  <div class="category-container">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">商品分类</span>
            <el-button type="primary" @click="handleAddCategory(null)">新增一级分类</el-button>
          </div>
          <div class="header-right">
            <el-button-group>
              <el-button @click="handleExpandAll">展开全部</el-button>
              <el-button @click="handleCollapseAll">折叠全部</el-button>
            </el-button-group>
            <el-button type="success" @click="handleSaveSort">保存排序</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="分类名称" min-width="200">
          <template #default="{ row }">
            <div class="category-name">
              <el-image
                v-if="row.icon"
                :src="row.icon"
                :preview-src-list="[row.icon]"
                fit="cover"
                class="category-icon"
              />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="分类编码" width="120" />
        <el-table-column prop="level" label="层级" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="row.level === 1 ? 'primary' : row.level === 2 ? 'success' : 'warning'">
              {{ row.level }}级
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100">
          <template #default="{ row }">
            <el-input-number
              v-model="row.sort"
              :min="0"
              :max="999"
              size="small"
              @change="handleSortChange"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodsCount" label="商品数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                v-if="row.level < 3"
                type="primary"
                link
                @click="handleAddCategory(row)"
              >
                新增子分类
              </el-button>
              <el-button
                type="primary"
                link
                @click="handleEditCategory(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                :disabled="row.goodsCount > 0"
                @click="handleDeleteCategory(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分类表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增分类' : '编辑分类'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级分类">
          <el-cascader
            v-model="formData.parentId"
            :options="categoryOptions"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              emitPath: false
            }"
            placeholder="请选择上级分类"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="分类图标" prop="icon">
          <el-upload
            class="category-icon-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeIconUpload"
            :on-success="handleIconSuccess"
            :on-error="handleUploadError"
          >
            <img v-if="formData.icon" :src="formData.icon" class="category-icon" />
            <el-icon v-else class="category-icon-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：200x200px，支持 jpg、png 格式</div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCategory" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getGoodsCategories,
  createGoodsCategory,
  updateGoodsCategory,
  deleteGoodsCategory,
  updateGoodsCategorySort,
  updateGoodsCategoryStatus
} from '@/api/goods'

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 分类列表
const categoryList = ref([])
const categoryOptions = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const formData = reactive({
  parentId: null,
  name: '',
  code: '',
  icon: '',
  sort: 0,
  status: 1,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 图片上传
const uploadUrl = '/api/merchant/upload'
const uploadHeaders = {
  // 设置上传请求头
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    const { data } = await getGoodsCategories()
    categoryList.value = data
    categoryOptions.value = [{ id: 0, name: '无', children: data }]
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 新增分类
const handleAddCategory = (parent) => {
  dialogType.value = 'add'
  formData.parentId = parent ? parent.id : null
  formData.name = ''
  formData.code = ''
  formData.icon = ''
  formData.sort = 0
  formData.status = 1
  formData.description = ''
  dialogVisible.value = true
}

// 编辑分类
const handleEditCategory = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = (row) => {
  ElMessageBox.confirm(
    '确定要删除该分类吗？删除后不可恢复',
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }
  ).then(async () => {
    try {
      await deleteGoodsCategory(row.id)
      ElMessage.success('删除成功')
      fetchCategories()
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }).catch(() => {})
}

// 保存分类
const handleSaveCategory = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    if (dialogType.value === 'add') {
      await createGoodsCategory(formData)
      ElMessage.success('创建成功')
    } else {
      await updateGoodsCategory(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存分类失败:', error)
      ElMessage.error('保存分类失败')
    }
  } finally {
    saving.value = false
  }
}

// 更新状态
const handleStatusChange = async (row) => {
  try {
    await updateGoodsCategoryStatus(row.id, row.status)
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 更新排序
const handleSortChange = () => {
  // 可以在这里添加防抖处理
}

// 保存排序
const handleSaveSort = async () => {
  try {
    const sortData = categoryList.value.map(item => ({
      id: item.id,
      sort: item.sort
    }))
    await updateGoodsCategorySort(sortData)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存排序失败:', error)
    ElMessage.error('保存排序失败')
  }
}

// 展开/折叠
const handleExpandAll = () => {
  // 实现展开全部逻辑
}

const handleCollapseAll = () => {
  // 实现折叠全部逻辑
}

// 图片上传相关
const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

const handleIconSuccess = (response) => {
  formData.icon = response.url
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 初始化
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.category-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-icon {
  width: 32px;
  height: 32px;
  border-radius: 4px;
}

.category-icon-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.category-icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 响应式布局优化 */
@media screen and (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-left,
  .header-right {
    width: 100%;
    justify-content: space-between;
  }
}
</style> 